package com.atguigu.daijia.customer.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    //注入远程调用接口
    @Autowired
    private CustomerInfoFeignClient customerInfoFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public String login(String code) {
        //拿着code进行远程调用
        Result<Long> loginResult = customerInfoFeignClient.login(code);

        //判断如果返回失败了，返回错误提示
        int codeResult = loginResult.getCode();
        if (codeResult != 200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //获取远程调用返回用户id
        Long id = loginResult.getData();

        //判断用户id是否为空，如果为空，提示
        if (id == null) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //生成token字符串
        String token = UUID.randomUUID().toString().replaceAll("-","");

        //将用户id放入Redis，设置过期时间
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token,
                             id.toString(),RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        //返回token
        return token;
    }

    public CustomerLoginVo getCustomerLoginInfo(Long id) {

        Result<CustomerLoginVo> customerLoginInfo = customerInfoFeignClient.getCustomerLoginInfo(id);

        Integer code = customerLoginInfo.getCode();
        if (code != 200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        CustomerLoginVo data = customerLoginInfo.getData();
        if (data == null) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return data;

    }
}
